package com.lzb.yabbs.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzb.yabbs.AppConfig;
import com.lzb.yabbs.R;
import com.lzb.yabbs.dao.UserInfo;
import com.lzb.yabbs.interfaces.OnFragmentInteractionListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link PersonalFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PersonalFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private TextView mUsernameTv;
    private CircleImageView mCircleImageView;

    private SharedPreferences sharedPreferences;
    private final static int LOGIN_REQUEST=0x123;
    private final static int LOGIN_SUCESS=0x142;
    private final static int LOGIN_FAIL=0x125;

    private LinearLayout mMsgLl;
    private TextView mMsgNumTv;

    private DisplayImageOptions  options;

    private boolean isLogin=false;

    private Button mLoginOutBtn;
    private Button mLoginInBtn;
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PersonalFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PersonalFragment newInstance(String param1, String param2) {
        PersonalFragment fragment = new PersonalFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public PersonalFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        sharedPreferences=getActivity().getSharedPreferences("login", Context.MODE_PRIVATE);

        options=new DisplayImageOptions.Builder().showImageOnLoading(null)
                .showImageOnFail(null)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_personal, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView(view);
        initDatas();
    }

    private void initDatas() {

        boolean isLogin=sharedPreferences.getBoolean("login",false);

        if(isLogin){
            setLoginBtnGone();
            mLoginOutBtn.setVisibility(View.VISIBLE);
            mUsernameTv.setText(sharedPreferences.getString("username","未登录"));
            ImageLoader.getInstance().displayImage(sharedPreferences.getString("avatar",AppConfig.MO_REN_avatar),mCircleImageView,options);
        }else {
            setLoginBtnGone();
            mLoginInBtn.setVisibility(View.VISIBLE);
        }
    }

    private void setLoginBtnGone(){
        mLoginOutBtn.setVisibility(View.GONE);
        mLoginInBtn.setVisibility(View.GONE);
    }

    private void initView(View view){
        mUsernameTv= (TextView) view.findViewById(R.id.username_tv);
        mCircleImageView= (CircleImageView) view.findViewById(R.id.avatar_civ);
        mLoginOutBtn= (Button) view.findViewById(R.id.login_out_btn);
        mLoginInBtn= (Button) view.findViewById(R.id.login_in_btn);
        mMsgLl= (LinearLayout) view.findViewById(R.id.msg_ll);
        mMsgNumTv= (TextView) view.findViewById(R.id.msg_num_tv);

        mLoginOutBtn.setOnClickListener(this);
        mLoginInBtn.setOnClickListener(this);
        LinearLayout mLoginLl= (LinearLayout) view.findViewById(R.id.login_ll);
        mLoginLl.setOnClickListener(this);
        mMsgLl.setOnClickListener(this);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        if(R.id.login_ll==v.getId()){
            if(!sharedPreferences.getBoolean("login",false)){
                Intent intent=new Intent(getActivity(),LoginActivity.class);
                startActivityForResult(intent,LOGIN_REQUEST);
            }
        }else if(R.id.login_out_btn==v.getId()){
            mUsernameTv.setText("未登录");
            mCircleImageView.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.ic_launcher));
            SharedPreferences.Editor editor=sharedPreferences.edit();
            editor.putBoolean("login",false);
            editor.commit();
            setLoginBtnGone();
            mLoginInBtn.setVisibility(View.VISIBLE);
        }else if(R.id.login_in_btn==v.getId()){
            if(!sharedPreferences.getBoolean("login",false)){
                Intent intent=new Intent(getActivity(),LoginActivity.class);
                startActivityForResult(intent,LOGIN_REQUEST);
            }
        }else if(R.id.msg_ll==v.getId()){

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==LOGIN_REQUEST&&resultCode==LOGIN_SUCESS){
            UserInfo userInfo= (UserInfo) data.getSerializableExtra("userinfo");
            SharedPreferences.Editor editor=sharedPreferences.edit();
            editor.putBoolean("login", true);
            editor.putString("username", userInfo.getUsername());
            editor.putString("token", userInfo.getToken());
            editor.putInt("uid", userInfo.getUid());
            editor.putString("avatar", userInfo.getAvatar());
            editor.commit();
            mUsernameTv.setText(userInfo.getUsername());
            System.out.println("avatar:" + userInfo.getAvatar());
            if(userInfo.getAvatar().equals("")||userInfo.getAvatar()==null||"null".equals(userInfo.getAvatar()))
                ImageLoader.getInstance().displayImage(AppConfig.MO_REN_avatar, mCircleImageView, options);
            else
                ImageLoader.getInstance().displayImage(userInfo.getAvatar(), mCircleImageView, options);
            isLogin=true;

            setLoginBtnGone();
            mLoginOutBtn.setVisibility(View.VISIBLE);
        }
    }
}
